﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ETModel {
    /// <summary>
    /// 对象引用存储(因为对象池的关系,组件会被回收再利用,实例如果被存储起来使用,每次使用都需要判断是否被回收,所以诞生了本结构体)
    /// </summary>
    /// <typeparam name="ObjectT"></typeparam>
    public struct ObjectRef<ObjectT>
        where ObjectT : Component {
        private long InitInsId;
        private ObjectT Obj;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="obj"></param>
        public ObjectRef(ObjectT obj) {
            Obj = obj;
            InitInsId = obj.InstanceId;
        }

        /// <summary>
        /// 获取对象的引用,如果对象已经被释放或者已回收,则返回null
        /// </summary>
        /// <returns></returns>
        public ObjectT GetObj() {
            if (Obj == null || Obj.IsDisposed || Obj.InstanceId != InitInsId) return null;
            return Obj;
        }

        public void Clear() {
            Obj = null;
        }
    }
}
